package day16MysSQL;

import java.io.FileReader;
import java.io.Reader;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {

    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    // 静态代码块
    static {
        try {
            // 1 使用 Properties 处理流
            // 使用 load()方法加载指定的流
            Properties props = new Properties();
            Reader is = new FileReader("db.properties");
            props.load(is);
            // 2 使用 getProperty(key)，通过 key 获得需要的值，
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            user = props.getProperty("user");
            password = props.getProperty("password");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 1-7
    public static Statement init() {
        try {
            // 1. 注册驱动
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            // 2.获得数据库连接
            Connection conn = DriverManager.getConnection(url, user, password);
            // 3.获取运行sql语句的执行对象
            return conn.createStatement();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public int executeUpdate(String sql) {
        // 4.执行sql语句(增 删 改) 返回受影响的行数
        try {
            Statement state = init();
            int rows = init().executeUpdate(sql);
            state.close();
            return rows;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public ResultSet executeQuery(String sql) {
        // 4.执行sql语句(查) 返回结果集
        try {
            Statement state = init();
            ResultSet res = state.executeQuery(sql);

            // state.close();

            return res;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
